package leyou.search.service.Impl;

import com.alibaba.fastjson.JSON;
import com.leyou.common.to.Goods;
import leyou.search.constant.Esconstant;
import leyou.search.service.EsGoodsService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class EsGoodsServiceImpl implements EsGoodsService {

    @Resource(name = "restHighLevelClient")
    private RestHighLevelClient client;

    /**
     * 保存商品到es
     * @param esModels
     * @return
     */
    @SneakyThrows
    @Override
    public Boolean bulkIndex(Goods esModels) {
        //批量操作的Request
        BulkRequest request = new BulkRequest();
        request.timeout("5m");
        //批量处理请求
            request.add(
                    new IndexRequest(Esconstant.PRODUCT_INDEX)
                            .id(esModels.getId().toString())
                            .source(JSON.toJSONString(esModels),XContentType.JSON));

        BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
        //response.hasFailures()是否是失败的  true为失败
        if(response.hasFailures()){
            log.info("向es中批量添加商品数据出错了=====>>>>>>>>prodcutSaveServiceImpl中");
        }
        return !response.hasFailures();
    }
}
